package com.lck.tutor.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lck.tutor.common.BaseResponse;
import com.lck.tutor.common.ErrorCode;
import com.lck.tutor.common.Result;
import com.lck.tutor.exception.BusinessException;
import com.lck.tutor.model.domain.Question;
import com.lck.tutor.model.domain.Record;
import com.lck.tutor.model.domain.User;
import com.lck.tutor.service.QuestionService;
import com.lck.tutor.mapper.QuestionMapper;
import com.lck.tutor.service.RecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
* @author Administrator
* @description 针对表【question(题目表)】的数据库操作Service实现
* @createDate 2022-10-20 15:49:24
*/
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
implements QuestionService{

    @Resource
    private RecordService recordService;

    @Override
    @Transactional
    public BaseResponse<String> submitAns(Question question, User loginUser) {
        String checked = question.getChecked();
        if (checked == null || checked.isEmpty()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请选择一个答案!");
        }
        if (checked.equals(question.getAnswer())){
            //此时，用户所提交的答案和题目答案一致
            int i = question.getFinish() + 1;
            question.setFinish(i) ;
            boolean isSuccess = updateById(question);
            if (isSuccess){
                Record record = new Record();
                String questionData = "第" + i + "次答题,正确答案：" + question.getAnswer() + "您的答案:" + question.getChecked();
                record.setQuestionData(questionData);
                record.setScore(100.0);
                record.setUserId(loginUser.getId());
                record.setSeconds(100000);
                record.setQuestionId(question.getId());
                record.setResult("正确");
                recordService.save(record);
            }
        } else {
            int i = question.getFinish() + 1;
            question.setFinish(i) ;
            question.setWrong(question.getWrong() + 1);
            boolean isSuccess = updateById(question);
            if (isSuccess){
                Record record = new Record();
                record.setQuestionData("第" + i +"次答题,正确答案："+question.getAnswer()+"您的答案:"+question.getChecked());
                record.setScore(0.0);
                record.setUserId(loginUser.getId());
                record.setSeconds(100000);
                record.setQuestionId(question.getId());
                record.setResult("错误");
                recordService.save(record);
            }
        }
        return Result.success("已提交");
    }
}
